package com.wzl.demo_08_02;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

public class MyService extends Service {
    //不绑定Service,返回null.但必须实现
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    //创建Service时调用
    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("MyService", "onCreate");
    }
    //启动Service时调用
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("MyService", "onStartCommand");
        Log.i("onStartCommand","flags:"+flags);
        Log.i("onStartCommand","startId:"+startId);//创建后每次调用startId值递增
        //开启一个线程,模拟耗时操作
        new Thread(){
            @Override
            public void run() {
                super.run();
                for (int i = 1; i <= 10; i++) {
                    Log.i("test", "i:" + i);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //this.stopself(); this指的是当前线程
                MyService.this.stopSelf();//停止当前Service
            }
        }.start();

        /*返回值
        * Service.START_NOT_STICKY  Service被杀死后不自动重启
        * Service.START_STICKY  Service被杀死后自动重启
        * Service.START_STICKY_COMPATIBILITY  Service被杀死后自动重启,兼容低版本
        * Service.START_REDELIVER_INTENT  重新发送Intent
        * Service.START_FLAG_REDELIVERY  重新发送Intent
        * Service.START_FLAG_RETRY  重新发送Intent
        * */
        return Service.START_REDELIVER_INTENT;
//        return super.onStartCommand(intent, flags, startId);
    }
    //销毁Service时调用
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("MyService", "onDestroy");
    }
}
